# -*- coding: utf-8 -*-
"""
@Time ： 2021/4/28 21:00
@Auth ： Mr. royalday 2487625775
@Company ： 2487625775@qq.cpm
@Function ：项目列表
"""
import time

from utils.tencent import cos
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, redirect
from web.forms.project import ProjectModelForm
from django.conf import settings
from web import models


def project_list(request):
    """
    项目列表
    :param request:
    :return:
    """
    if request.method == "GET":
        """
        1. 从数据库中获取两部分数据
            我创建的所有项目：已星标、未星标
            我参与的所有项目：已星标、未星标
        2. 提取已星标
            列表 = 循环 [我创建的所有项目] + [我参与的所有项目] 把已星标的数据提取    
        得到三个列表：星标、创建、参与
        """
        project_dict = {'star': [], 'my': [], 'join': []}

        my_project_list = models.Project.objects.filter(creator=request.tracer.user)
        join_project_list = models.ProjectUser.objects.filter(user=request.tracer.user)

        for row in my_project_list:
            if row.star:
                project_dict['star'].append({'value': row, 'type': 'my'})
            else:
                project_dict['my'].append({'value': row, 'type': 'my'})

        for item in join_project_list:
            if item.star:
                project_dict['star'].append({'value': item.project, 'type': 'join'})
            else:
                project_dict['join'].append({'value': item.project, 'type': 'join'})
        form = ProjectModelForm(request)
        return render(request, "project_list.html", {'form': form, 'project_dict': project_dict})

    if request.method == "POST":
        form = ProjectModelForm(request, data=request.POST)
        if form.is_valid():
            # 验证通过：项目名称、颜色、描述+creator创建者
            form.instance.creator = request.tracer.user

            # 创建项目的同时创建一个cos桶，并将桶名称、区域保存至项目记录中
            mobile_phone = request.tracer.user.mobile_phone  # 重写的方法会自动在后面添加时间戳及appid
            time_stamp = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())

            # name = form.cleaned_data['name']
            bucketName = str(mobile_phone) + "-" + time_stamp + '-' + settings.TENCENT_COS['appid']
            region = settings.TENCENT_COS['region']
            cos.create_bucket(bucketName=bucketName, region=region)

            # 添加桶信息到数据库
            form.instance.bucket = bucketName
            form.instance.region = region

            # 创建项目记录
            form.save()
            # 如果创建项目成功，用户名下的项目数量加1
            user = request.tracer.user
            user.project_num += 1
            user.save()
            return JsonResponse({'status': True})

    return JsonResponse({'status': False, 'error': form.errors})


def project_star(request, project_type, project_id):
    """
    项目添加星标
    :param request:
    :param project_type: 项目类型：我创建的、我参与的
    :param project_id: 项目id
    :return:
    """
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=True)
        return redirect('web:project_list')
    if project_type == 'join':
        models.ProjectUser.objects.filter(id=project_id, user=request.tracer.user).update(star=True)
        return redirect('web:project_list')

    return HttpResponse("请求错误！！！")


def project_remove_star(request, project_type, project_id):
    """
    项目取消星标
    :param request:
    :param project_type: 项目类型：我创建的、我参与的
    :param project_id: 项目id
    :return:
    """
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=False)
        return redirect('web:project_list')
    if project_type == 'join':
        models.ProjectUser.objects.filter(id=project_id, user=request.tracer.user).update(star=False)
        return redirect('web:project_list')

    return HttpResponse("请求错误！！！")
